package switchviz.network.snmp;

import java.awt.BorderLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.IOException;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.apache.log4j.Logger;
import org.jdom.JDOMException;

import switchviz.core.ResourceManager;
import switchviz.gui.component.JLabeldComponent;
import switchviz.gui.component.JXMLComboBox;
import switchviz.network.netswitch.SwitchDataModel;
import switchviz.util.FileOperations;

public class SnmpWalkerFrame extends JFrame implements ActionListener, WindowListener
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 4600203822913903454L;
	private static Logger logger = Logger.getLogger(SnmpWalkerFrame.class);
	private JTextArea _txtArea = null;
	private JLabeldComponent _txtoid = null;
	private JButton _buttstart = null;
	private JButton _buttstop = null;
	private JButton _buttclose = null;
	private JButton _buttsaveas = null;
	private SnmpWalkerWorker _walkerworker = null;
	private JXMLComboBox _cmbswitch = null;
	
	public SnmpWalkerFrame()
	{
		super("SNMP Walker");
		this.setSize(1024, 768);
		this.setIconImage(ResourceManager.getInstance().getImageIconSignal().getImage());
		try
		{
			initialize();
			this.setVisible(true);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			logger.error(e);
		}
	}
	
	public SnmpWalkerFrame(SwitchDataModel datamodel)
	{
		this();
		for(int i = 0; i < _cmbswitch.getComboBox().getItemCount(); ++i)
		{
			Object obj = _cmbswitch.getComboBox().getItemAt(i);
			if(((SwitchDataModel)obj).getName().equals(datamodel.getName()))
			{
				_cmbswitch.getComboBox().setSelectedItem(obj);
				break;
			}
		}
	}
	
	public SnmpWalkerFrame(String oid)
	{
		this();
		_txtoid.setText(oid);
	}
	
	private void initialize() throws JDOMException, IOException
	{
		JPanel panel = new JPanel();
		panel.setLayout(ResourceManager.getInstance().getBorderLayout());
		
		_txtArea = new JTextArea();
		_txtArea.setWrapStyleWord(true);
		_txtArea.setLineWrap(true);
		_txtArea.setMargin(new Insets(1, 4, 1, 4));
		_txtArea.setEditable(false);
		JScrollPane scrollpane = new JScrollPane(_txtArea);
		_txtoid = new JLabeldComponent("Start OID: ", JLabeldComponent.TEXTFIELD);
		_txtoid.setText("1");
		_cmbswitch = new JXMLComboBox("Switch: ", JXMLComboBox.SWITCHLIST);
		
        _buttstart = new JButton("Start SNMP Walk");
        _buttstart.setActionCommand(ResourceManager.getInstance().getActionApply());
        _buttstart.addActionListener(this);
        _buttstop = new JButton("Stop");
        _buttstop.setActionCommand(ResourceManager.getInstance().getActionStop());
        _buttstop.addActionListener(this);
        _buttstop.setEnabled(false);
        _buttclose = new JButton("Close");
        _buttclose.setActionCommand(ResourceManager.getInstance().getActionCancel());
        _buttclose.addActionListener(this);
        _buttsaveas = new JButton("Save As");
        _buttsaveas.setActionCommand(ResourceManager.getInstance().getActionSave());
        _buttsaveas.addActionListener(this);
        
        JPanel optionpanel = new JPanel();
        optionpanel.setLayout(new BoxLayout(optionpanel, BoxLayout.LINE_AXIS));
        optionpanel.add(_txtoid);
        optionpanel.add(_cmbswitch);
        
        JPanel buttonpanel = new JPanel();
        buttonpanel.setLayout(new BoxLayout(buttonpanel, BoxLayout.LINE_AXIS));
        buttonpanel.add(Box.createHorizontalGlue());
        
        buttonpanel.add(_buttstart);
        buttonpanel.add(_buttstop);
        buttonpanel.add(_buttsaveas);
        buttonpanel.add(_buttclose);
        
        panel.add(optionpanel, BorderLayout.NORTH);
        panel.add(scrollpane, BorderLayout.CENTER);
        panel.add(buttonpanel, BorderLayout.SOUTH);
		
        this.add(panel);
        this.addWindowListener(this);
	}

	public void actionPerformed(ActionEvent evt) 
	{
		String command = evt.getActionCommand();
		if(command.equals(ResourceManager.getInstance().getActionApply()))
		{
			if(_cmbswitch.getComboBox().getSelectedIndex() == -1) return;
			_buttstop.setEnabled(true);
			_buttsaveas.setEnabled(false);
			if(_walkerworker != null)
			{
				close();
				_txtArea.setText("");
			}
			String oid = _txtoid.getText();
			_walkerworker = new SnmpWalkerWorker(_txtArea, oid, (SwitchDataModel)_cmbswitch.getComboBox().getSelectedItem());
			_walkerworker.execute();
		}
		else if(command.equals(ResourceManager.getInstance().getActionStop()))
		{
			_buttstop.setEnabled(false);
			close();
			_buttsaveas.setEnabled(true);
		}
		else if(command.equals(ResourceManager.getInstance().getActionCancel()))
		{
			close();
			this.setVisible(false);
		}
		else if(command.equals(ResourceManager.getInstance().getActionSave()))
		{
			_buttstart.setEnabled(false);
			try
			{
				
				final JFileChooser fc = new JFileChooser(ResourceManager.getInstance().getViewFolder());
				int retval = fc.showDialog(this, "Save SNMP Walk");
				if(retval == JFileChooser.APPROVE_OPTION)
					saveSNMPWalk(fc.getSelectedFile());
				
			}
			catch(Exception e)
			{
				logger.error("Can't save current View! " + e.getMessage());
				e.printStackTrace();
			}
			_buttstart.setEnabled(true);
		}
	}
	
	private void saveSNMPWalk(File file)
	{
		if(logger.isInfoEnabled())
			logger.info("Save SNMP Walk to File " + file.getAbsolutePath());
		try
		{
			_txtArea.write(FileOperations.getISOWriter(file));
		}
		catch(Exception e)
		{
			logger.error(e);
		}
	}
	
	private void close()
	{
		if(_walkerworker != null)
		{
			try
			{
				_walkerworker.stop();
				_walkerworker.cancel(true);
			}
			catch(Exception e)
			{
				logger.error(e);
			}
		}
	}

	public void windowClosed(WindowEvent evt) 
	{
		close();
	}
	
	public void windowClosing(WindowEvent evt) 
	{
		close();
	}
	
	public void windowActivated(WindowEvent arg0) {}
	public void windowDeactivated(WindowEvent arg0) {}
	public void windowDeiconified(WindowEvent arg0) {}
	public void windowIconified(WindowEvent arg0) {}
	public void windowOpened(WindowEvent arg0) {}
}
